package util

import (
	"fmt"
	"math"
)

func Start(n int,m int) int{

	maxn := int(math.Pow(10, 5))
	maxm := int(math.Pow(10, 6))

	if n<1 || n>maxn || m<1 || m>maxm{ //输入非法
		fmt.Println("非法")
		return -1
	}
	var nums []int //参加游戏的人编号
	for i:=0;i<n;i++{
		nums = append(nums,i)
	}

	fmt.Println(nums,m)

	if len(nums) >= m {
		nums = game_01(nums,m)
	}

	if len(nums)>1{
		nums = game_02(nums,m)
	}
	fmt.Println("n=",n,"  ","m=",m)
	fmt.Println("胜利者编号:",nums[0])
	return 0
}


func game_01(tempnums []int,m int) []int{ //一次删除多个节点，重塑nums
	multiple := len(tempnums)/m
	remainder := len(tempnums)%m

	var remainderElems []int
	if remainder > 0{
		index := m*multiple-1
		remainderElems = tempnums[index+1:]
		tempnums = tempnums[:index+1]
	}

	for i:=multiple;i>=1;i--{
		delIndex := m*i-1
		tempnums = append(tempnums[:delIndex],tempnums[delIndex+1:]...)
	}

	if len(remainderElems)>0{
		tempnums = append(remainderElems,tempnums...)
	}

	fmt.Println(tempnums,m)

	if len(tempnums)>=m{
		return game_01(tempnums,m)//直到 n <= m
	}else{
		return tempnums
	}
}

func game_02(tempnums []int,m int) []int{ //n-1个m的长度 一次完成剩余删除，删除len(nums)-1个节点，剩余1个胜利玩家
	cycle := 0
	if m % len(tempnums)==0{
		cycle = m / len(tempnums)-1
	}else{
		cycle = m / len(tempnums)
	}
	index := m - len(tempnums)*(cycle) - 1
	if index < len(tempnums)-1{
		tempnums = append(tempnums[index+1:],tempnums[:index]...)
	}else{
		tempnums = append(tempnums[:index])
	}
	fmt.Println(tempnums,m)
	if len(tempnums)>1 {
		return game_02(tempnums,m)
	}else{
		return tempnums
	}
}